/**
 * @description  自动入池监控
 * @author shenhong
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Modal } from 'antd';
import { ContentPackage, TableC, DATA_ENTRY, AdvancedSearch, ModalC, PrimaryC, PrimaryGhostC } from '../../../../comps';
import MyModal from '../tools/index';
import style from './index.less';
import colorArr from '../../../../css/colors.js';
import _ from 'lodash';
@Form.create()
class AutoMonitor extends PureComponent {
  constructor() {
    super();
    this.state = {
      isVisible: false, // 是否展示modal框
      type: '', // 传给组建的类型
      isReset: false, // 是否重置
      formData: {},
      sortedInfo: {}, // 排序信息
      unitPerCent: [
        'valuation_rate_of_return',
        'yield_in_the_past_month',
        'yield_in_recent_three_months',
        'yield_in_the_past_six_months',
        'yearly_one_year_yield',
        'yield_since_establishment',
      ], //单位是百分号的维度
      unitPerCent1: [
        'net_valuation',
        'valuation_full_price',
        'operating_cash_flow_per_share',
        'undistributed_profit_per_share',
        'capital_reserve_per_share',
        'net_assets_per_share',
        'basic_earnings_per_share',
      ], //单位是元的维度
    };
  }
  componentDidMount() {
    const { dispatch } = this.props;
    const {
      globalM: { dataDictionary = {} },
    } = this.props;
    dispatch({
      type: 'autoMonitorM/save', // 获取字典值
      payload: {
        selectData: dataDictionary,
      },
    });
    dispatch({
      // 获取全量的券池名称
      type: 'autoMonitorM/searchAll',
      payload: { pageInfo: { currentPage: 1, numInPage: 20 } },
    });
    dispatch({
      type: 'autoMonitorM/getTableData',
      payload: { currentPage: 1, numInPage: 20 },
    });
  }

  // 查询数据
  searchData = (e) => {
    const { formData } = this.state;
    const query = formData;
    if (formData.startDate) {
      query.startDate = formData.startDate.format('YYYY-MM-DD');
    }
    if (formData.endDate) {
      query.endDate = formData.endDate.format('YYYY-MM-DD');
    }
    query.currentPage = 1;
    query.numInPage = 20;
    this.props.dispatch({
      type: 'autoMonitorM/getTableData',
      payload: query,
    });
  };

  // 表格改变事件
  tableCahnge = (pagination, filt, sorter) => {
    const { isReset, formData } = this.state;
    if (!isReset) {
      this.setState({
        sortedInfo: sorter,
      });
      const query = formData;
      if (formData.startDate) {
        query.startDate = formData.startDate.format('YYYY-MM-DD');
      }
      if (formData.endDate) {
        query.endDate = formData.endDate.format('YYYY-MM-DD');
      }
      query.currentPage = pagination.current;
      query.numInPage = pagination.pageSize;
      if (sorter.order !== undefined) {
        query.orderByField = sorter.columnKey;
        query.order = sorter.order;
      } else {
        delete query.sortOrder;
        delete query.columnsKey;
      }
      this.props.dispatch({
        type: 'autoMonitorM/getTableData',
        payload: query,
      });
    } else {
      message.warning('已重置查询条件，请重新查询');
    }
  };

  // 取消
  handleCancel = () => {
    if (this.state.type == 'see') {
      this.setState({ isVisible: false });
    } else {
      this.setState({ isVisible: false }, () => {
        this.child.resetDatas();
      });
    }
  };

  // 提交or保存
  handleOk = (e) => {
    const data = this.child.getData();
    if (data !== undefined) {
      const query = data;
      query.type = e == '0' ? 'SAVE' : 'SAVE_AND_COMMIT';
      this.props.dispatch({
        type: 'couponPoolApprovalM/autoAdd',
        payload: query,
        callback: (res) => {
          if (res.code == 0) {
            this.props.dispatch({
              type: 'autoMonitorM/getTableData',
              payload: { currentPage: 1, numInPage: 20 },
            });
            this.setState({
              isVisible: false,
            });
          }
        },
      });
    }
  };

  shuBtn = () => {
    const { loading } = this.props;
    return (
      <div>
        {this.state.type !== 'see' ? (
          <div className='footerArea'>
            <div className='footOne' style={{ display: 'inline-block' }}>
              {' '}
              <PrimaryGhostC title='取消' onClick={this.handleCancel} />
            </div>
            <div className='footTwo' style={{ display: 'inline-block' }}>
              {' '}
              <PrimaryGhostC title='保存' loading={loading.effects['couponPoolApprovalM/getAddAndEdit']} onClick={() => this.handleOk('0')} />
            </div>
            <div className='footThree' style={{ display: 'inline-block' }}>
              <PrimaryC title='提交' loading={loading.effects['couponPoolApprovalM/getAddAndEdit']} onClick={() => this.handleOk('1')} />
            </div>
          </div>
        ) : null}
      </div>
    );
  };
  // modal框
  showModal = () => {
    const { datas, type, filterItemId, recordId, isVisible } = this.state;
    const { loading } = this.props;
    const text = type == 'see' ? '查看' : '重新发起'; // 根据传给组建的类型展示对应的标题
    const newProps = {
      visible: isVisible,
      title: `${text}`,
      width: 1000,
      footer:
        type == 'see'
          ? null
          : [
              <PrimaryGhostC key='footOne' onClick={this.handleCancel} title='取消' />,
              <PrimaryC key='save' onClick={() => this.handleOk('0')} style={{ marginLeft: '10px' }} loading={loading.effects['couponPoolApprovalM/getAddAndEdit']} title='保存' />,
              <PrimaryC
                key='commit'
                onClick={() => this.handleOk('1')}
                style={{ marginLeft: '10px' }}
                loading={loading.effects['couponPoolApprovalM/getAddAndEdit']}
                title='提交'
              />,
            ],
    };
    return (
      <div>
        {isVisible ? (
          <ModalC
            {...newProps}
            onCancel={this.handleCancel}
            // className={style.ModalBody}
            // footer={this.shuBtn()}
          >
            <MyModal
              type={type} // 是什么操作（新增，查看，编辑，出池，重新发起）
              onRef={(ref) => (this.child = ref)} // 父组件对本组件的引用
              filterItemId={filterItemId}
              recordId={recordId}
            />
          </ModalC>
        ) : null}
      </div>
    );
  };
  // 查看
  seeData = (e) => {
    const { dispatch } = this.props;
    this.setState({
      recordId: e.flowSecurityPoolId,
      filterItemId: e.id,
      isVisible: true,
      type: 'see',
    });
  };

  // 重新发起
  requestData = (e) => {
    const { dispatch } = this.props;
    this.setState({
      recordId: e.flowSecurityPoolId,
      filterItemId: e.id,
      isVisible: true,
      type: 'request',
    });
  };

  // 改变条目状态颜色
  changeColor = (text) => {
    const colors = colorArr.debtAndProfit.text;
    let color = text == 1 ? colors[6] : text == 2 ? colors[1] : colors[4];
    let tet = text == 1 ? '待生效' : text == 2 ? '生效中' : '已失效';
    return <span style={{ color: `${color}` }}>{`${tet}`}</span>;
  };

  // 改变券池类型展示样式
  changePoolType = (text) => {
    const {
      autoMonitorM: { selectData },
    } = this.props;
    const poolType = selectData.SECURITYPOOL_ASSETCLASS;
    let tet = '';
    if (poolType && poolType.length) {
      poolType.map((item) => {
        if (item.code == text) {
          tet = item.value;
        }
      });
    }
    return tet;
  };
  // 维度翻译
  changeText = (text, selectGropu) => {
    let tet = '';
    if (selectGropu && selectGropu.length) {
      selectGropu.map((item) => {
        if (item.code == text) {
          tet = item.value;
        }
      });
    }
    return tet;
  };
  // 符号翻译
  changeSymbol = (text, symbol) => {
    let tet = '';
    if (symbol && symbol.length) {
      symbol.map((item) => {
        if (text == item.code) {
          tet = item.value;
        }
      });
    }
    return tet;
  };
  //内容翻译
  changeContent = (defaultData) => {
    let tet = '';
    if (this.state.unitPerCent.some((i) => i == defaultData.dimension)) {
      tet = +defaultData.content * 100 + '%';
    } else if (defaultData.dimension == 'fund_size') {
      //基金规模，单位亿元
      tet = +defaultData.content / 100000000 + '亿';
    } else if (defaultData.dimension == 'circulation_market_value') {
      //流通市值，单位万元
      tet = +defaultData.content / 10000 + '万';
    } else if (this.state.unitPerCent1.some((i) => i == defaultData.dimension)) {
      tet = defaultData.content + '元';
    } else if (defaultData.dimension == 'remaining_period') {
      //剩余期限
      tet = defaultData.content + 'Y';
    } else {
      tet = defaultData.content;
    }
    return tet;
  };
  // 改变条目规则展示样式
  changeRule = (record) => {
    const {
      autoMonitorM: { selectData },
    } = this.props;
    const selectGropu =
      record.securityType == 'bond'
        ? selectData.flow_filter_dimension_bond
        : record.securityType == 'fund'
        ? selectData.flow_filter_dimension_fund
        : selectData.flow_filter_dimension_stock;
    const symbolAll = selectData.flow_filter_operation_symbol;
    let newRule = [];
    record.autoItems.map((item) => {
      const dimension = this.changeText(item.dimension, selectGropu);
      const symbol = this.changeSymbol(item.symbol, symbolAll);
      const content = this.changeContent(item);
      const newContent = dimension + symbol + content;
      newRule.push(newContent);
    });

    return newRule.join('且');
  };
  // 改变columns
  changeColumns = (arr) => {
    const { sortedInfo } = this.state;
    const datas = arr;
    if (datas.length && datas[datas.length - 1].title != '操作') {
      datas.push({
        title: '操作',
        dataIndex: 'id',
        width: '10%',
        key: 'id',
        type: 'operate',
        operates: [
          {
            title: '查看',
            onClick: (record) => this.seeData(record),
          },
          {
            title: '重新发起',
            onClick: (record) => this.requestData(record),
            rules: {
              hide: {
                relation: 'and',
                items: [{ key: 'entryStatus', value: ['3'], relation: ['!='] }], //  已保存以外均不可编辑
              },
            },
          },
        ],
      });
      datas.map((item) => {
        if (item.key == 'entryStatus') {
          item.width = '9%';
          item.render = (text, record) => {
            return this.changeColor(text);
          };
        }
        if (item.key == 'effectiveTime') {
          item.sorter = true;
          item.width = '9%';
          item.sortOrder = sortedInfo.columnKey == 'effectiveTime' && sortedInfo.order;
        }
        if (item.key == 'expirationTime') {
          item.width = '9%';
          item.sorter = true;
          item.sortOrder = sortedInfo.columnKey == 'expirationTime' && sortedInfo.order;
        }
        if (item.key == 'securityType') {
          item.width = '9%';
          item.render = (text, record) => {
            return this.changePoolType(text);
          };
        }
        if (item.key == 'entryRule') {
          item.render = (text, record) => {
            return this.changeRule(record);
          };
        }
      });
    }
    return datas;
  };

  // 表格
  tableRender = () => {
    const {
      autoMonitorM: { tableData },
    } = this.props;
    const dataSource = tableData.dataSource;
    const pageInfo = tableData.pageInfo;
    const newColumns = this.changeColumns(tableData.columns);

    return (
      <div style={{ marginTop: '10px' }}>
        <TableC
          columns={newColumns}
          dataSource={dataSource}
          current={pageInfo.currentPage}
          total={pageInfo.total}
          pageSize={pageInfo.numInPage}
          onChange={this.tableCahnge}
          selfScrollY={true}
        />
      </div>
    );
  };

  // 券池名称转义
  changePoolName = (e) => {
    const datas = [];
    if (e && e.length) {
      e.map((item) => {
        datas.push({ title: item.name, value: item.id });
      });
    }
    return datas;
  };
  // 改变券池类型数据格式
  changeType = (arr) => {
    const data = [];
    if (arr && arr.length) {
      arr.map((item) => {
        data.push({ title: item.value, value: item.code });
      });
    }
    return data;
  };

  render() {
    const {
      autoMonitorM: { selectData, poolName },
    } = this.props;
    const poolNameU = this.changePoolName(poolName);
    const selectType = this.changeType(selectData.SECURITYPOOL_ASSETCLASS);
    const entry = [
      { title: '待生效', value: '1' },
      { title: '生效中', value: '2' },
      { title: '已失效', value: '3' },
    ];
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'securityPoolId',
          title: '券池名称',
          type: DATA_ENTRY.SELECT,
          dataSource: poolNameU,
          allowClear: true,
        },
        {
          dataIndex: 'poolType',
          title: '券池类型',
          type: DATA_ENTRY.SELECT,
          dataSource: selectType,
          allowClear: true,
        },
        {
          dataIndex: 'status',
          title: '条目状态',
          type: DATA_ENTRY.SELECT,
          dataSource: entry,
          allowClear: true,
        },
        {
          dataIndex: ['startDate', 'endDate'],
          title: '生效区间',
          type: DATA_ENTRY.RANGEDATE,
          allowClear: true,
          disableFuture: false,
          onRef: (ref) => this.setState({ RANGEDATE: ref }),
        },
      ],
      onQuery: (e) => {
        this.setState({ formData: e, isReset: false }, (e) => {
          this.searchData(e);
        });
      },
      onClear: () => {
        const { form } = this.props;
        const { formData } = this.state;
        form.resetFields();
        if (JSON.stringify(formData) !== '{}') {
          this.setState({ isReset: true });
        } else {
          this.setState({
            isReset: false,
          });
        }
      },
    };
    return (
      <ContentPackage
        title='自动入池监控'
        contentHtml={
          <div className={style.body_Area}>
            <div>
              <AdvancedSearch {...searchProps} />
            </div>
            {this.tableRender()}
            {this.showModal()}
          </div>
        }
      />
    );
  }
}
export default connect(({ autoMonitorM, loading, globalM }) => ({ autoMonitorM, loading, globalM }))(AutoMonitor);
